﻿using log4net;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Tools;
using WPF数据采集系统.Base;
using WPF数据采集系统.Model;
using WPF数据采集系统.View;
using WPF数据采集系统.ViewModel;

namespace WPF数据采集系统
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public static RadioButton MainViewButton;
        public static string LANGEUAGE = PlcTool.IniRead("Language", "默认语言", System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\OmronPLCAddress.ini");
        public static string ThemeColor = PlcTool.IniRead("Theme", "默认主题", System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\OmronPLCAddress.ini");
        public static string MainViewName = PlcTool.IniRead("Project", "默认项目", System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\OmronPLCAddress.ini");
        public static string RotateModel = PlcTool.IniRead("SystemDefault", "旋转机默认规格", System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\OmronPLCAddress.ini");
        public static bool AutoLogin = Convert.ToBoolean(PlcTool.IniRead("SystemDefault", "自动操作员登录", System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\OmronPLCAddress.ini"));
        public static string LoginUser = "admin";
        public static string LoginRole = "admin";
        public static MainViewModel mvm = null;
        public MainWindow()
        {
            InitializeComponent();
            ThemeChange(ThemeColor);
            LanguageChange(LANGEUAGE);
        }
        private void WindowClose_Click(object sender, RoutedEventArgs e)
        {
            if (LANGEUAGE == "zh-cn")
            {
                if (CustomMsgBox.ShowDialog("退出程序", "是否确认要关闭(退出)程序？", CustomMsgBoxButton.Two, CustomMsgBoxImage.Error).IsYes)
                {
                    ListBoxHelper.listBoxAdd(mvm.logListBox, "用户：" + LoginUser + " 退出了程序。", true);
                    ScanerHook.PostMessage(ScanerHook.HWND_BROADCAST, ScanerHook.WM_INPUTLANGCHANGEREQUEST, IntPtr.Zero, ScanerHook.LoadKeyboardLayout(ScanerHook.cn_ZH, ScanerHook.KLF_ACTIVATE));
                    Application.Current.Shutdown();
                    //this.Close();
                }
            }
            else
            {
                if (CustomMsgBox.ShowDialog("Exit Program", "Are you sure you want to close (exit) the program?", CustomMsgBoxButton.Two, CustomMsgBoxImage.Alert).IsYes)
                {
                    ListBoxHelper.listBoxAdd(mvm.logListBox, "User：" + LoginUser + " Quit the program.", true);
                    ScanerHook.PostMessage(ScanerHook.HWND_BROADCAST, ScanerHook.WM_INPUTLANGCHANGEREQUEST, IntPtr.Zero, ScanerHook.LoadKeyboardLayout(ScanerHook.cn_ZH, ScanerHook.KLF_ACTIVATE));
                    Application.Current.Shutdown();
                    //this.Close();
                }
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
            {
                string CustomTitle = "警告";
                string msg = "缩放后可能导致内容显示不全，是否确认要将界面进行缩放？";
                if (MainWindow.LANGEUAGE != "zh-cn")
                {
                    CustomTitle = "Warning";
                    msg = "Zooming may cause incomplete content display. Are you sure you want to zoom the interface?";

                }
                if (CustomMsgBox.ShowDialog(CustomTitle, msg, CustomMsgBoxButton.Two, CustomMsgBoxImage.Alert).IsYes)
                {
                    this.WindowState = WindowState.Normal;
                }
            }
            else
            {
                this.WindowState = WindowState.Maximized;
            }
        }
        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
                this.DragMove();
        }

        private void ScreenMin_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }
        /// <summary>
        /// 切换用户后先进入主页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StackPanel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            string his_user = LoginUser;
            UserPowerChange upc = new UserPowerChange();
            upc.sendMessage += ReceivedMessage;
            upc.ShowDialog();
            if (LoginUser != his_user)
            {
                radioMainView.IsChecked = true;
                mvm.OnTabChanged(MainViewName);
                ListBoxHelper.listBoxAdd(mvm.logListBox, "登录用户由:" + his_user + " 切换为:" + LoginUser + " 成功!", true);
            }
        }
        private void ReceivedMessage(string username, string role, string MVName)
        {
            string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            LoginUser = username;
            LoginRole = role;
            login_user_name.Text = LoginUser;
        }
        int i = 0;
        private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            i += 1;
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 0, 0, 300);
            timer.Tick += (s, e1) => { timer.IsEnabled = false; i = 0; };
            timer.IsEnabled = true;
            if (i % 2 == 0)
            {
                timer.IsEnabled = false;
                i = 0;
                this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
            }
        }

        private void ContentControl_Loaded(object sender, RoutedEventArgs e)
        {
            login_user_name.Text = LoginUser;
        }
        private DoubleAnimation c_daListAnimation;
        public bool c_bState = true;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            c_daListAnimation = new DoubleAnimation();
            try
            {
                if (AutoLogin)
                {
                    LoginUser = "operator";
                    LoginRole = "LoginRole";
                }
                if (LoginUser == null || LoginRole == null)
                {
                    UserPowerChange upc = new UserPowerChange();
                    upc.sendMessage += ReceivedMessage;
                    upc.ShowDialog();
                }
                if (LoginUser == null || LoginRole == null)
                {
                    ScanerHook.PostMessage(ScanerHook.HWND_BROADCAST, ScanerHook.WM_INPUTLANGCHANGEREQUEST, IntPtr.Zero, ScanerHook.LoadKeyboardLayout(ScanerHook.cn_ZH, ScanerHook.KLF_ACTIVATE));
                    CustomMsgBox.ShowDialog("未登录警告", "用户未登录,程序将自动退出！(The program exits automatically when the user is not logged in!)", CustomMsgBoxButton.One, CustomMsgBoxImage.Alert);
                    ListBoxHelper.listBoxAdd(mvm.logListBox, "用户未登录,程序自动退出!", true);
                    Application.Current.Shutdown();
                    this.Close();
                }
                else
                {
                    mvm = new MainViewModel(MainViewName);
                    MainViewButton = radioMainView;
                    this.DataContext = mvm;
                    ListBoxHelper.listBoxAdd(mvm.logListBox, "用户:" + LoginUser + "登录了程序", true);
                }
            }
            catch (Exception ex)
            {
                CustomMsgBox.ShowDialog("ERROR", ex.Message, CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
                ScanerHook.PostMessage(ScanerHook.HWND_BROADCAST, ScanerHook.WM_INPUTLANGCHANGEREQUEST, IntPtr.Zero, ScanerHook.LoadKeyboardLayout(ScanerHook.cn_ZH, ScanerHook.KLF_ACTIVATE));
                Application.Current.Shutdown();
                this.Close();
            }
        }

        private void HideLeftMenu(object sender,RoutedEventArgs e)
        {
            
            if (c_bState)
            {
                c_bState = false;
                c_daListAnimation.From = 0;
                c_daListAnimation.To = -400;
                cd.Width = new GridLength(75);

            }
            else
            {
                c_bState = true;
                c_daListAnimation.From = -400;
                c_daListAnimation.To = 230;
                cd.Width = new GridLength(230);
            }
        }

        private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            if (LANGEUAGE == "zh-cn")
            {
                LanguageChange("en-us");
                mvm.Language = LANGEUAGE = "en-us";
                PlcTool.IniWrite("Language", "默认语言", "en-us", path + "\\OmronPLCAddress.ini");
            }
            else
            {
                LanguageChange("zh-cn");
                mvm.Language = LANGEUAGE = "zh-cn";
                PlcTool.IniWrite("Language", "默认语言", "zh-cn", path + "\\OmronPLCAddress.ini");
            }
            //ApplySkinFromMenuItem("/WPF数据采集系统;component/Assets/Styles/DefaultStyles1.xaml", "/WPF数据采集系统;component/Assets/Styles/DefaultStyles.xaml");
            //换肤
        }

        private void LanguageChange(string language)
        {
            List<ResourceDictionary> dictionaryList = new List<ResourceDictionary>();
            foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries)
            {
                if (dictionary.Source != null)
                {
                    dictionaryList.Add(dictionary);
                }
            }
            string requestedCulture = null;
            if (language == "en-us")
            {
                requestedCulture = @"/WPF数据采集系统;component/Language/en-us.xaml";
            }
            else if (language == "zh-cn")
            {
                requestedCulture = @"/WPF数据采集系统;component/Language/zh-cn.xaml";

            }
            ResourceDictionary resourceDictionary = dictionaryList.FirstOrDefault(d => d.Source.OriginalString.Equals(requestedCulture));
            Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary);
            Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
        }
        private void ThemeChange(string ThemeColor)
        {
            string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            List<ResourceDictionary> dictionaryList = new List<ResourceDictionary>();
            foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries)
            {
                if (dictionary.Source != null)
                {
                    dictionaryList.Add(dictionary);
                }
            }
            string themes = null;
            if (ThemeColor == "black")
            {
                BtnSoftwareVersion.IsChecked = true;
                themes = @"/WPF数据采集系统;component/Assets/Styles/Themes_black.xaml";
                PlcTool.IniWrite("theme", "默认主题", "black", path + "\\OmronPLCAddress.ini");
            }
            else if (ThemeColor == "light")
            {
                BtnSystemConfiguration.IsChecked = true;
                themes = @"/WPF数据采集系统;component/Assets/Styles/Themes_light.xaml";
                PlcTool.IniWrite("theme", "默认主题", "light", path + "\\OmronPLCAddress.ini");
            }
            else if (ThemeColor == "purple")
            {
                BtnLogRecord.IsChecked = true;
                themes = @"/WPF数据采集系统;component/Assets/Styles/Themes_purple.xaml";
                PlcTool.IniWrite("theme", "默认主题", "purple", path + "\\OmronPLCAddress.ini");
            }
            else
            {
                BtnThremGreen.IsChecked = true;
                themes = @"/WPF数据采集系统;component/Assets/Styles/Themes_green.xaml";
                PlcTool.IniWrite("theme", "默认主题", "green", path + "\\OmronPLCAddress.ini");
            }
            ResourceDictionary resourceDictionary = dictionaryList.FirstOrDefault(d => d.Source.OriginalString.Equals(themes));
            Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary);
            Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\LogFile";
            string FileName = DateTime.Now.ToString("yyyyMMdd_") + "log.txt";
            string PathAndFileName = path + "\\" + FileName;
            try
            {
                System.Diagnostics.Process.Start(PathAndFileName);
            }
            catch (Exception ex)
            {
                CustomMsgBox.ShowDialog(ex.Message);
            }

        }
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\LogFile";
            string FileName = DateTime.Now.ToString("yyyyMMdd_") + "log.txt";
            string PathAndFileName = path + "\\" + FileName;
            try
            {
                System.Diagnostics.Process.Start(path);
            }
            catch (Exception ex)
            {
                CustomMsgBox.ShowDialog(ex.Message);
            }
        }
        private void RadioButtonChecked(object sender, RoutedEventArgs e)
        {
            var radioButton = sender as RadioButton;
            if (radioButton == null)
                return;
            string Themes = radioButton.Content.ToString();
            if (Themes.Contains("black"))
            {
                ThemeChange("black");
            }
            else if (Themes.Contains("light"))
            {
                ThemeChange("light");
            }
            else if (Themes.Contains("purple"))
            {
                ThemeChange("purple");
            }
            else
            {
                ThemeChange("green");
            }
        }
        /// <summary>
        /// 记录IsChecked上次的值，默认为False
        /// </summary>
        bool rememberChecked = false;

        /// <summary>
        /// “设置”按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButSetText_Click(object sender, RoutedEventArgs e)
        {
            if (rememberChecked)
            {
                butSetText.IsChecked = false;
                rememberChecked = false;
            }
            else
            {
                butSetText.IsChecked = true;
                rememberChecked = true;
            }
        }
        /// <summary>
        /// "设置明细"失去焦点时发生事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetTextelPopup_LostFocus(object sender, RoutedEventArgs e)
        {
            butSetText.IsChecked = false;
            butSetText.IsEnabled = true;
            rememberChecked = false;
        }
        /// <summary>
        /// "设置明细"隐藏时发生事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetTextelPopup_Closed(object sender, EventArgs e)
        {
            butSetText.IsChecked = false;
            butSetText.IsEnabled = true;
            rememberChecked = false;
        }
        /// <summary>
        /// "设置明细"显示时发生事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetTextelPopup_Opened(object sender, EventArgs e)
        {
            butSetText.IsEnabled = false;
        }

        private void Border_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {

        }

        private void Directory_BT_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
